import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import styles from '../../assets/style/PostNote.module.css';
import { httpPostNote } from '../../request/http';
import { Query } from '../../../utils/Query.js';
import { Button, Modal, Input, Table, message } from 'antd';
const { TextArea } = Input;
import { createBrowserHistory } from 'history';

const PostNote = (props) => {
	let map = useSelector((state) => state.baseMap.map);
	const userid = useSelector((state) => state.userid.value);
	const $dispatch = useDispatch();
	const [isModalVisible, changeVisible] = useState(false); //控制弹窗显隐
	const [isPostshow, setPostshow] = useState(false); // 发布公告的弹窗显隐
	const [isRepost, setRepost] = useState(false);
	const [service] = useState({ docName: 'guanggu', layerId: 0 });
	const [isdrawRoadbuffer, setIsDrawbuffer] = useState(false); //是否处于绘制缓冲线阶段  如果处于该阶段，不能再点击发布公告
	let BaseUrl = 'gdbp://MapGisLocal/wuhan/sfcls/';
	let bufferUrl = '';
	const [source, setSource] = useState(null); //绘制画笔的数据源
	let clipBufferUrl = ''; // 最终裁剪后缓冲区的url
	const [bufferInfo, setBufferInfo] = useState([]); // 查询的缓冲区与居民区相交的要素信息,用于绑定table
	const [infoAll, setInfoAll] = useState([]); //bufferInfo的全部数据，用于备份
	const [note, setNote] = useState(''); //公告内容
	const history = createBrowserHistory();
	useEffect(() => {
		if (props.itemkey == 4) {
			changeVisible(true);
		}
	}, [props.itemkey]);
	/* 确认添加状况道路 */
	const handleOk = () => {
		queryResident();
		changeVisible(false);
	};
	/* 查询居民区 */
	const queryResident = () => {
		Query.queryAreas({
			service: service,
			callback: queryAreasSuccess,
		});
	};
	// 查询居民区后的回调
	const queryAreasSuccess = (result) => {
		//初始化Zondy.Format.PolygonJSON类
		var format = new Zondy.Format.PolygonJSON();
		//将MapGIS要素JSON反序列化为ol.Feature类型数组
		var features = format.read(result);
		let drawLayers = [];
		for (let i = 0; i < features.length; i++) {
			// 定义居民区的随机颜色
			let R = parseInt(Math.random() * 256);
			let G = parseInt(Math.random() * 256);
			let B = parseInt(Math.random() * 256);
			let randcolor = `rgb(${R},${G},${B})`;
			let drawSource = new ol.source.Vector({
				wrapX: false,
			});
			drawSource.addFeatures([features[i]]);
			let drawLayer = new ol.layer.Vector({
				source: drawSource,
				title: '居民区高亮',
				style: new ol.style.Style({
					fill: new ol.style.Fill({
						color: randcolor,
					}),
					//边线样式
					stroke: new ol.style.Stroke({
						color: 'blue',
						width: 1,
					}),
				}),
			});
			drawLayers.push(drawLayer);
		}

		drawLayers.map((item) => {
			map.addLayer(item);
		});
		/* 渲染完成后切换中心点至居民区 */
		let view = map.getView();
		view.setZoom(16);
		view.setCenter([114.392, 30.491]);

		// // 绘制完毕后，添加交互式画笔，绘制道路缓冲区
		setIsDrawbuffer(true);
		drawRoadlines();
	};
	/* 绘制道路线 */
	const drawRoadlines = () => {
		setSource(
			new ol.source.Vector({
				wrapX: false, //false 让地图 x 不能无限拉长
			})
		);
		const layer = new ol.layer.Vector({
			source: source,
		});
		map.addLayer(layer);
		//  添加画笔
		let draw = new ol.interaction.Draw({
			source: source,
			type: 'LineString', // 线类型
		});
		// 激活画笔
		map.addInteraction(draw);
		draw.on('drawend', (e) => {
			let pointarr = e.feature.getGeometry().getCoordinates();
			var pointObj = [];
			pointarr.map((item) =>
				pointObj.push(new Zondy.Object.Point2D(item[0], item[1]))
			);
			/* 绘制完成后根据绘制的线生成缓冲区 */
			map.removeInteraction(draw);
			get_buffer_byRoadlines(pointObj);
		});
	};
	/* 基于绘制的道路线生成缓冲区*/
	const get_buffer_byRoadlines = (pointObj) => {
		//构成折线的弧段
		let gArc = new Zondy.Object.Arc(pointObj);
		//构成线的折线
		let gAnyLine = new Zondy.Object.AnyLine([gArc]);
		//设置线要素的几何信息
		let gline = new Zondy.Object.GLine(gAnyLine);
		//设置要素的几何信息
		let fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] });
		//设置属性结构
		const regAttStr = new Zondy.Object.CAttStruct({
			FldName: ['ID', '周长', 'LayerID'],
			FldNumber: 3,
			FldType: ['FldLong', 'FldDouble', 'FldLong'],
		});
		const values = [1, 0.132101984752282, 8];
		//实例化CAttDataRow类
		const valuesRow = new Zondy.Object.CAttDataRow(values, 1);
		//实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
		const clsBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
			ip: 'localhost',
			port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
			//设置要素缓冲分析左半径
			leftRad: 0.001,
			//设置要素缓冲分析右半径
			rightRad: 0.001,
		});
		const resultName = BaseUrl + 'buffer' + Date.now();
		bufferUrl = resultName;
		// console.log(bufferUrl)
		/*设置缓冲分析参数*/
		//设置几何信息
		clsBufBySR.sfGeometryXML = JSON.stringify([fGeom]);
		//设置属性结构
		clsBufBySR.attStrctXML = JSON.stringify(regAttStr);
		//设置属性值
		clsBufBySR.attRowsXML = JSON.stringify([valuesRow]);
		//设置追踪半径
		clsBufBySR.traceRadius = 0.0001;
		//设置缓冲结果的名称以及存放地址
		clsBufBySR.resultName = resultName;
		//调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析
		clsBufBySR.execute(bufferSuccess, 'post', false, 'json');
	};
	// 将缓冲区添加到图层
	const bufferSuccess = (result) => {
		if (result.succeed) {
			const resultLayer = new Zondy.Map.GdbpLayer('', [bufferUrl], {
				ip: 'localhost',
				port: 6163,
				isBaseLayer: false,
			});
			// this.map.addLayer(resultLayer)
			clipBufferbyResident();
		}
	};
	// 对缓冲区进行裁剪，将缓冲区与居民区相交的部分保留下来
	const clipBufferbyResident = () => {
		clipBufferUrl = BaseUrl + 'ClipBuffer' + Date.now();
		//实例化ClipByLayer类
		const clipParam = new Zondy.Service.ClipByLayer({
			ip: 'localhost',
			port: '6163',
			//源居民区的URL
			srcInfo1: BaseUrl + '居民区',
			//裁剪缓冲区的URL
			srcInfo2: bufferUrl,
			//设置结果URL
			desInfo: clipBufferUrl,
			infoOptType: 0,
		});
		//调用基类的execute方法，执行图层裁剪分析。Success为成功回调函数
		clipParam.execute(clipSuccess, 'post', false, 'json');
	};
	const clipSuccess = (result) => {
		if (result.succeed) {
			//将结果图层添加到地图视图中显示
			const resultClipLayer = new Zondy.Map.GdbpLayer('', [clipBufferUrl], {
				ip: 'localhost',
				port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
				crossOrigin: 'Anonymous',
			});
			map.addLayer(resultClipLayer);
			queryBufferInfo();
		} else {
			// alert('叠加分析失败，请检查参数！');
		}
	};
	/* 裁剪成功后，查询缓冲区图层的信息 */
	const queryBufferInfo = () => {
		Query.querybygdbUrl(clipBufferUrl, queryBufferSuccess);
	};
	const dataSource = [];
	const columns = [
		{
			title: '序号',
			dataIndex: 'index',
			key: 'index',
		},
		{
			title: '受影响的地区',
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: '物业电话',
			dataIndex: 'phonenumber',
			key: 'phonenumber',
		},
	];
	const queryBufferSuccess = (result) => {
		console.log(result.SFEleArray);
		if (result.SFEleArray.length != 0) {
			setPostshow(true);
			result.SFEleArray.map((i, index) => {
				const item = {};
				item.key = `${index}`;
				item.index = index + 1;
				item.name = i.AttValue[4];
				item.phonenumber = i.AttValue[5];
				dataSource.push(item);
			});
			setBufferInfo(dataSource);
			setInfoAll(dataSource);
			// getCategory()
		} else {
			setRepost(true);
		}
	};
	const handleCancel = () => {
		changeVisible(false);
		props.resetItemkey();
	};
	/* 确定发布 */
	const okPost = () => {
		if (note) {
			const affected_area = bufferInfo
				.map((item) => {
					return item.name;
				})
				.join(',');
			httpPostNote('/notice', {
				user_id: userid,
				notice_content: note,
				affected_area: affected_area,
			}).then((res) => {
				console.log(res);
				const { code } = res;
			});
			setPostshow(false);
			/* 发布完成后刷新页面 */
			// history.go(0)
		} else {
			message.error('您还没有添加公告信息，请确认输入');
		}
	};
	const cancelPost = () => {
		history.go(0);
	};
	const okRepost = () => {
		setRepost(false);
		source.clear();
		drawRoadlines();
	};
	const cancelRepost = () => {
		history.go(0);
	};
	const updateNote = (e) => {
		setNote(e.target.value);
	};

	return (
		<div className={styles.container}>
			<Modal
				title="请在显示的居民区内添加状况道路"
				visible={isModalVisible}
				onOk={handleOk}
				onCancel={handleCancel}
				okText="确定"
				cancelText="取消"
			></Modal>
			<Modal
				title="发布公告"
				visible={isPostshow}
				onOk={okPost}
				onCancel={cancelPost}
				okText="确定发布"
				cancelText="取消发布"
			>
				<div>
					<Input placeholder="请输入关键字"></Input>
					<Table dataSource={bufferInfo} columns={columns} />
					<p>公告内容</p>
					<TextArea
						rows={4}
						value={note}
						onChange={updateNote}
						placeholder="请输入公告内容"
					/>
				</div>
			</Modal>
			<Modal
				title="缓冲区里没有包含居民区,是否重新添加"
				visible={isRepost}
				onOk={okRepost}
				onCancel={cancelRepost}
				okText="确定"
				cancelText="取消"
			></Modal>
		</div>
	);
};

export default PostNote;
